package xin.ryven.car.android.utils

import android.graphics.Bitmap
import android.graphics.Color
import androidx.palette.graphics.Palette

object ColorUtils {
    data class ThemeColors(
        val backgroundColor: Int,
        val accentColor: Int
    )
    
    fun extractThemeColors(bitmap: Bitmap): ThemeColors {
        val palette = Palette.from(bitmap).generate()
        
        // 获取深色的背景色
        val backgroundColor = palette.getDarkVibrantColor(palette.getDarkMutedColor(Color.parseColor("#1A1A1A")))
        
        // 获取高亮的强调色
        val accentColor = palette.getVibrantColor(palette.getLightVibrantColor(Color.WHITE))
        
        // 确保背景色足够暗
        val darkenedBackground = ensureDarkness(backgroundColor, 0.3f)
        
        // 确保强调色足够亮且与背景形成对比
        val brightAccent = ensureBrightness(accentColor, 0.7f)
        
        return ThemeColors(darkenedBackground, brightAccent)
    }
    
    private fun ensureDarkness(color: Int, maxBrightness: Float): Int {
        val hsv = FloatArray(3)
        Color.colorToHSV(color, hsv)
        
        // 如果亮度太高，降低亮度
        if (hsv[2] > maxBrightness) {
            hsv[2] = maxBrightness
        }
        
        return Color.HSVToColor(hsv)
    }
    
    private fun ensureBrightness(color: Int, minBrightness: Float): Int {
        val hsv = FloatArray(3)
        Color.colorToHSV(color, hsv)
        
        // 如果亮度太低，提高亮度
        if (hsv[2] < minBrightness) {
            hsv[2] = minBrightness
        }
        
        return Color.HSVToColor(hsv)
    }
    
    /**
     * 判断颜色是否为浅色
     */
    fun isLightColor(color: Int): Boolean {
        val hsv = FloatArray(3)
        Color.colorToHSV(color, hsv)
        // 如果亮度大于0.5，认为是浅色
        return hsv[2] > 0.5f
    }
} 